package org.example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Description: JWT 拦截器
 * @Author: 曹震
 * @Date: 2024/11/23 15:48
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        // 放行登录和注册接口
        if (requestURI.equals("userControl/login") || requestURI.equals("userControl/register")) {
            return true;
        }

        // 获取 Authorization 字段
        String token = request.getHeader("Authorization");


        // 检查 Token 是否存在
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Authorization token is missing");
            return false;
        }

        // 去除 Bearer 前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        try {
            // 解析 Token（你应确保 JwtToken.parseToken 返回 Jws<Claims>）
            Jws<Claims> jwsClaims = JwtToken.parseToken(token);
            Claims claims = jwsClaims.getBody();

            // 检查 Token 是否过期
            if (JwtToken.isTokenExpired(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Token has expired");
                return false;
            }

            // 检查 Token 是否即将过期（用 claims）
            if (JwtToken.isTokenExpiringSoon(claims)) {
                // 延长 Token 有效期
                String newToken = JwtToken.extendTokenExpiration(claims);
                // 放到响应头
                response.setHeader("Authorization", "Bearer " + newToken);
            }

            // 如果 Token 有效，继续处理请求
            return true;
        } catch (JwtException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Invalid token");
            return false;
        }
    }
}
